package com.yzz.hzraisedust.hzraseidust.main.pmdetail;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yzz.hzraisedust.hzraseidust.R;
import com.yzz.hzraisedust.hzraseidust.main.BaseActivity;
import com.yzz.hzraisedust.hzraseidust.modelbean.PmDetailItemBean;
import com.yzz.hzraisedust.hzraseidust.modelbean.RequstItemBean;
import com.yzz.hzraisedust.hzraseidust.util.Constant;
import com.yzz.hzraisedust.hzraseidust.util.NetUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

public class PmDetailActivity extends BaseActivity implements Response.Listener<String>,Response.ErrorListener{

    private ListView mListView;
    private LineChartView mLineCharView;
    private List<PointValue> mPointValues = new ArrayList<PointValue>();
    private List<AxisValue> mAxisXValues = new ArrayList<AxisValue>();

    private String mSN;
    private RequstItemBean<PmDetailItemBean> mPmItems;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pm_detail);
        showLoginingDlg();
        initView();
        initLoginingDlg();
        showLoginingDlg();
        mSN = getIntent().getStringExtra(Constant.SN_UPPER_KEY);
        //请求网络
        NetUtil netUtil = new NetUtil(PmDetailActivity.this);
        Map<String,String> params = new HashMap<>();
        params.put(Constant.UID_LOWER_KEY,Constant.Uid);
        params.put(Constant.SN_UPPER_KEY,mSN);
        netUtil.requestData(this,this, Constant.PMDETAIL_URL,params);


    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initView() {
        mLineCharView = findViewById(R.id.pm_line_char_view);
        mListView = findViewById(R.id.pm10_value_list);
    }
    private int maxValue = 500;
    /**
     * 设置X 轴的显示
     */
    private void getAxisXLables(){
        for (int i = 0; i < mPmItems.getRows().size(); i++) {
            PmDetailItemBean item = mPmItems.getRows().get(i);
            if(item.getPm10()>maxValue){
                maxValue = (int)item.getPm10();
            }
            mAxisXValues.add(new AxisValue(i).setLabel(""));
        }
    }

    /**
     * 图表的每个点的显示
     */
    private void getAxisPoints(){
        for (int i = 0; i < mPmItems.getRows().size(); i++) {
            mPointValues.add(new PointValue(i, mPmItems.getRows().get(i).getPm10()));
        }
    }
    private void initLineChart(){
        Line line = new Line(mPointValues).setColor(Color.parseColor("#FFCD41"));  //折线的颜色（橙色）
        List<Line> lines = new ArrayList<Line>();
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
        line.setCubic(true);//曲线是否平滑，即是曲线还是折线
        line.setFilled(false);//是否填充曲线的面积
        line.setHasLabels(true);//曲线的数据坐标是否加上备注
//      line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(false);//是否显示圆点 如果为false 则没有原点只有点显示（每个数据点都是个大的圆点）
        lines.add(line);
        LineChartData data = new LineChartData();
        data.setLines(lines);

        //坐标轴
        Axis axisX = new Axis(); //X轴
        axisX.setHasTiltedLabels(true);  //X坐标轴字体是斜的显示还是直的，true是斜的显示
        axisX.setTextColor(Color.BLACK);  //设置字体颜色
        //axisX.setName("date");  //表格名称
        axisX.setTextSize(10);//设置字体大小
        axisX.setMaxLabelChars(8); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisXValues.length
        axisX.setValues(mAxisXValues);  //填充X轴的坐标名称
        data.setAxisXBottom(axisX); //x 轴在底部
        //data.setAxisXTop(axisX);  //x 轴在顶部
        axisX.setHasLines(true); //x 轴分割线

        // Y轴是根据数据的大小自动设置Y轴上限(在下面我会给出固定Y轴数据个数的解决方案)
        Axis axisY = new Axis();  //Y轴
        axisY.setName("");//y轴标注
        axisY.setTextSize(10);//设置字体大小
        data.setAxisYLeft(axisY);  //Y轴设置在左边

        //data.setAxisYRight(axisY);  //y轴设置在右边


        //设置行为属性，支持缩放、滑动以及平移
        mLineCharView.setInteractive(true);
        // mLineCharView.setZoomType(ZoomType.HORIZONTAL);
        //  mLineCharView.setMaxZoom((float) 2);//最大方法比例
        //  mLineCharView.setContainerScrollEnabled(true, ContainerScrollType.HORIZONTAL);
        mLineCharView.setLineChartData(data);
        mLineCharView.setVisibility(View.VISIBLE);
        /**注：下面的7，10只是代表一个数字去类比而已
         * 当时是为了解决X轴固定数据个数。见（http://forum.xda-developers.com/tools/programming/library-hellocharts-charting-library-t2904456/page2）;
         */
        Viewport v = new Viewport(mLineCharView.getMaximumViewport());v.bottom = 0;
        v.bottom = 0;
        v.top = maxValue;
        mLineCharView.setMaximumViewport(v);
        v.left = 0;
        v.right= mPmItems.getRows().size()-1;
        mLineCharView.setCurrentViewport(v);
    }

    @Override
    public void onResponse(String s) {
        closeLoginingDlg();
        Type type = new TypeToken<RequstItemBean<PmDetailItemBean>>(){}.getType();
        Gson gson = new Gson();
        mPmItems = gson.fromJson(s,type);
        if(mPmItems!=null && mPmItems.isSuccess()) {
            PMDetailAdapter adapter = new PMDetailAdapter(PmDetailActivity.this, mPmItems.getRows());
            mListView.setAdapter(adapter);

            getAxisXLables();//获取x轴的标注
            getAxisPoints();//获取坐标点
            initLineChart();//初始化
        }else{
            Toast.makeText(PmDetailActivity.this,"出现错误:"+mPmItems.getMessage(),Toast.LENGTH_LONG).show();
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
       if(keyCode == KeyEvent.KEYCODE_BACK){

           finish();
           return  true;
       }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onErrorResponse(VolleyError volleyError) {
        Toast.makeText(this,"发生错误",Toast.LENGTH_LONG).show();
        closeLoginingDlg();
        finish();
    }
}
